import org.apache.calcite.adapter.jdbc.JdbcSchema;
import org.apache.calcite.config.CalciteConnectionProperty;
import org.apache.calcite.jdbc.CalciteConnection;
import org.apache.calcite.schema.SchemaPlus;
import org.apache.calcite.schema.impl.AbstractSchema;
import org.apache.calcite.schema.impl.ScalarFunctionImpl;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class UserDefineFunc {
    public static void main(String[] args) throws SQLException {
        Connection connection = DriverManager.getConnection("jdbc:calcite:");

        // Unwrap our connection using the CalciteConnection
        CalciteConnection calciteConnection = connection.unwrap(CalciteConnection.class);

        calciteConnection.getProperties().setProperty(CalciteConnectionProperty.CASE_SENSITIVE.camelName(), "false");

        // Get a pointer to our root schema for our Calcite Connection
        SchemaPlus rootSchema = calciteConnection.getRootSchema();

        // Instantiate a data source, this can be autowired in using Spring as well
        DataSource mysqlDataSource = JdbcSchema.dataSource(
                "jdbc:mysql://localhost:3306/local_test",
                "com.mysql.cj.jdbc.Driver", // Change this if you want to use something like MySQL, Oracle, etc.
                "root", // username
                "123456"   // password
        );


        // Attach our Postgres Jdbc Datasource to our Root Schema
        //rootSchema.add(POSTGRESQL_SCHEMA, JdbcSchema.create(rootSchema, POSTGRESQL_SCHEMA, postgresDataSource, null, null));

        // Attach our MySQL Jdbc Datasource to our Root Schema
        //rootSchema.add(MYSQL_SCHEMA, JdbcSchema.create(rootSchema, MYSQL_SCHEMA, mysqlDataSource, null, null));

        SchemaPlus post = rootSchema.add("custom_function", new AbstractSchema());

        post.add("my_function", ScalarFunctionImpl.create(MySquareFunction.class, "eval"));


        //将自定义函数注册到 custom_function 空间中，使用 custom_function.functionName 调用。


        //String customSql = "select custom_function.my_function(\"age\") as age2 from mysql.\"human\" h";

    }

    public static class MySquareFunction {
        public int eval(int a) {
            return a * a;
        }
    }

}
